let absSelect;
$(function () {
    loadDataSource();
    var sqlEditor = CodeMirror.fromTextArea(document.getElementById("sqlEditor"), {
        mode: "text/x-sparksql", // spark sql模式
        tabSize:4,
        styleActiveLine: true,
        lineNumbers: true,  //显示行号
        theme: "dracula",   //设置主题
        lineWrapping:true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], //添加行号栏，折叠栏
        matchBrackets: true, //括号高亮匹配
        extraKeys: {
            "Tab": "autocomplete", // tab键自动补全
            'Ctrl-U': formatSQL,  // Ctrl+F 实现格式化
        },
        // hintOptions: {
        //     tables: {
        //         "table1_xxx": ['id'],
        //         "table2_xxx": ['id', 'name']
        //     }
        // },
    });
    function formatSQL(){
        let originSQL ="";
        originSQL = this.sqlEditor.getValue();
        this.sqlEditor.setValue(sqlFormatter.format(originSQL));
    }
    sqlEditor.on('keyup', (cm, event) => {
        if (event.keyCode >= 65 && event.keyCode <= 90){
            cm.showHint();
        }
    });

    const SQL_CUSTOM_KEYWORDS = ['color', 'datasource'];
    SQL_CUSTOM_KEYWORDS.forEach(words => {
        CodeMirror.resolveMode("text/x-sparksql").keywords[words] = true;
    });




    $("#btn_generator").on('click',function () {
        //Project Initializr
        let projectName = $.trim($("#project_name_id").val());
        let targetPath = $.trim($("#save_path_id").val());
        // SpringBoot Version
        let springBootVersion = $("input[name='springBootVersion']:checked").val();
        // Project Metadata
        let groupValue = $.trim($("#group_value").val());
        let artifactValue = $.trim($("#artifact_value").val());
        let nameValue = $.trim($("#name_value").val());
        let descriptionValue = $.trim($("#description_value").val());
        let packageNameValue = $.trim($("#package_name_value").val());
        let javaJar = $.trim($("#javaJar").val());
        let javaVersion = $("input[name='jdkVersion']:checked").val();
        let dbUrlId = $.trim($("#db_url_id").val());
        let dbName = $.trim($("#db_name").val());
        let dbUserName = $.trim($("#db_user_name").val());
        let dbPass = $.trim($("#db_pass").val());
        let isSecurity = $("input[name='role']:checked").val()

        // validate input
        let errorFlag = false;
        $(".validate").each(function () {
            if($.trim($(this).val())==''){
                $(this).removeClass('input-type').addClass('input-type-error');
                errorFlag = true;
            }else{
                $(this).removeClass('input-type-error').addClass('input-type');
            }
        })
        if(errorFlag){
            return;
        }

        $("body").mLoading({text:"代码生成中，请勿关闭..."});//显示loading组件
        let params = {
            projectName: projectName,
            targetPath: targetPath,
            springBootVersion: springBootVersion,
            groupValue: groupValue,
            artifactValue: artifactValue,
            nameValue: nameValue,
            descriptionValue: descriptionValue,
            packageNameValue: packageNameValue,
            javaJar: javaJar,
            javaVersion: javaVersion,
            dbUrlId:dbUrlId,
            dbName:dbName,
            dbUserName:dbUserName,
            dbPass:dbPass,
            moduleType:isSecurity
        };


        $.ajax({
            url: '/initProject',
            type: 'POST',
            data:params,
            dataType: 'json',
            success: function(resp){
                $("body").mLoading("hide");
                if(resp.code==200){
                    alert("SUCCESS");
                }else{
                    alert("操作失败");
                }

            }
        });

    })
    $("#source_btn").on('click',function () {
        let params = {
            dbSourceName: $.trim($("#jdbcName").val()),
            dbSourceUrl: $.trim($("#jdbcUrl").val()),
            dbUserName: $.trim($("#dbPoint").val()),
            dbPassWord: $.trim($("#dbPass").val())
        };
        $.ajax({
            url: '/insertDataSource',
            type: 'POST',
            contentType :'application/json',
            data:JSON.stringify(params),
            dataType: 'json',
            success: function(resp){
               if(resp.code==200){
                   alert("SUCCESS");
                   loadDataSource();
               }else{
                   alert("操作失败");
               }
            }
        });
    })
    $("#del_btn").on('click',function () {
        let params = {
            id: $.trim($("#dataSource").val()),
        };
        $.ajax({
            url: '/delDataSource',
            type: 'POST',
            data:params,
            dataType: 'json',
            success: function(resp){
                if(resp.code==200){
                    alert("SUCCESS");
                    loadDataSource();
                }else{
                    alert("操作失败");
                }
            }
        });
    })
    $("#con_btn").on('click',function () {
        $("body").mLoading({text:"数据库连接中，请勿关闭..."});//显示loading组件
        let params = {
            id: $.trim($("#dataSource").val()),
        };
        $.ajax({
            url: '/conDataSource',
            type: 'POST',
            data:params,
            dataType: 'json',
            success: function(resp){
                $("body").mLoading("hide");
                if(resp.code==200){
                    var setting = {	};

                    var data = new Array();
                    $.each(resp.data.tablesList,function (index,value) {
                        var params={
                            name:value.tableName,
                            icon:"/static/img/table.png",
                            children:value.columns
                        }
                        data.push(params)
                    })

                    var zNodes =[
                        { name:"表结构", open:true, icon:"/static/img/db.png",
                            children: data
                        },
                    ];

                    $.fn.zTree.init($("#treeDemo"), setting, zNodes);
                          var tables = {
                            tables: resp.data.tablesMap
                        }
                    sqlEditor.setOption("hintOptions",tables)
                    // 获取表明
                    $("#bean_id,#multi_bean_id,#multi_bean_id_vo").empty();
                    $("#bean_id,#multi_bean_id,#multi_bean_id_vo").append('<option value="">--请选择数据库表--</option>')


                    if(!$("#bean_id").is(":visible")){
                        var template = doT.template($("#multi_select_table_template").text());

                        $("#multi_last_template").html(template({data:resp.data.tablesList}))

                    }
                    $.each(resp.data.tablesList,function(i,v){
                        $("#bean_id,#multi_bean_id,#multi_bean_id_vo").append('<option value="'+v.tableName+'">'+v.tableName+'</option>')
                    });
                }else{
                    alert("操作失败");
                }

            }
        });
    })

    function getCharCount(str,char){
        var regex = new RegExp(char, 'g'); // 使用g表示整个字符串都要匹配
        var result = str.match(regex);          //match方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
        var count=!result ? 0 : result.length;
        return count;
    }
    // run sql
    $("#run_btn").on('click',function(){

        let sql =sqlEditor.getSelection()==""?sqlEditor.getValue():sqlEditor.getSelection();
        let id = $("#dataSource").val();
       if(getCharCount(sql,"SELECT")>1){
           alert("请选择一条语句进行执行");
           return;
       }
        if(id==""){
            alert("请选择要链接的数据源");
            return;
        }


        let params = {
            id: $.trim(id),
            sql:$.trim(sql)
        };
        $.ajax({
            url: '/runSqlResult',
            type: 'POST',
            data:params,
            dataType: 'json',
            success: function(resp){
                if(resp.code==200){
                    const columnData = new Array()

                    $.each(resp.data.columnsTables,function (index,value) {
                        let column = {
                            key: value,
                            text: value
                        }
                        columnData.push(column)
                    });
                    var responseData = {
                        "data":resp.data.list
                    }

                    resultGrid(columnData,responseData)
                }else{
                    alert("操作失败");
                }
            }
        });
    });
    absSelect = new verjs_select();
    $("#bean_id,#multi_bean_id").on('change',function () {
        let beanName = $(this).val().substring(0,2);
        if(beanName==='t_'){
            beanName = $(this).val().substring(2);
        }else{
            beanName = $(this).val();
        }
        let tempName = toHumpName(beanName);
        let finalName = tempName.substring(0,1).toUpperCase()+tempName.substring(1)

        $("#class_bean,#multi_class_bean").val(finalName)

        var data={
            id:$.trim($("#dataSource").val()),
            table:$(this).val()
        }

        $.ajax({
            url: '/getTablesBean',
            type: 'POST',
            data:data,
            dataType: 'json',
            success: function(resp){
                if(resp.code==200){
                    $("#search").empty();
                    let data = new Array()
                    //多表生成不进行具体bean 查询
                    $("#bean_id_vo").append('<option value="">--选择字段--</option>')
                    $.each(resp.data,function(i,v){
                        $("#bean_id_vo").append('<option value="'+v.name+'">'+v.name+'</option>')
                        let _option={
                            id:v.name,
                            name:v.name
                        }
                        data.push(_option);
                    });
                    if(!$("#bean_id").is(":visible")){
                        $("#searchMainVo").empty();
                        absSelect.render({
                            elem: "#searchMainVo",
                            data: data,
                            init_value: [1],
                            body_height: 300,
                            checkbox: true,
                            name: "test"
                        });
                        return
                    };
                    var template = doT.template($("#select_table_template").text());

                    $("#last_template").html(template({data:resp.data}))


                    absSelect.render({
                        elem: "#search",
                        data: data,
                        init_value: [1],
                        body_height: 300,
                        checkbox: true,
                        name: "test"
                    });
                    absSelect.render({
                        elem: "#search2",
                        data: data,
                        init_value: [1],
                        body_height: 300,
                        checkbox: true,
                        name: "test"
                    });
                }else{
                    alert("操作失败");
                }
            }
        });
    })


    $("#btn_code_generator").on('click',function () {
        let classType =[];
        $("input[name='classType']:checked").each(function () {
            classType.push($(this).val());
        })
        let searchKey =[];
        $(".search-key:visible").each(function () {
            let columns = $(this).find("select[name='filed']").val()
            let columns_key = $(this).find("select[name='key']").val()
            if(columns!="" && columns_key!=""){
                let last_value = columns+"#"+columns_key;
                searchKey.push(last_value);
            }

        });


        var data={
            sourceId:$.trim($("#dataSource").val()),
            filePath:$.trim($("#filePath").val()),
            packageName:$.trim($("#packageName").val()),
            tableName:$.trim($("#bean_id").val()),
            entityName:$.trim($("#class_bean").val()),
            voName:absSelect.get_form_value('search').test,
            dtoName: absSelect.get_form_value('search2').test,
            httpUrl:$.trim($("#httpUrl").val()),
            classType:classType.join(','),
            searchKey:searchKey.join(","),
            searchSql:$("#singleSql").val()
        }
        $("body").mLoading({text:"代码生成中，请勿关闭..."});//显示loading组件
        $.ajax({
            url: '/singleTableCreate',
            type: 'POST',
            data:data,
            dataType: 'json',
            success: function(resp){
                $("body").mLoading("hide");
                if(resp.code==200){
                    alert("SUCCESS");

                }else{
                    alert(resp.message);
                }
            },
            error:function (e) {
                $("body").mLoading("hide");
            }
        });
    })
    // 多表生成
    $("#btn_multi_code_generator").on('click',function () {
            const subTableMapping = [];
             const voList =[];
        $('.sub-key:visible').each(function(){
            let subTable = $(this).find("select[name='filed']").val();
            let subTableRelId = $(this).find("select[name='key']").val();
            let subVoId = $(this).find("input[name='searchVo']").attr("id");
            let subVoList = absSelect.get_form_value("searchVo"+subVoId).test;
            subTableMapping.push(subTable+"#"+"true"+"#"+subTableRelId);
            voList.push(subTable+"@"+subVoList);

        })


        let classType =[];
        $("input[name='classType']:checked").each(function () {
            classType.push($(this).val());
        })
        $("body").mLoading({text:"数据处理中，请勿关闭..."});//显示loading组件
        var data={
            sourceId:$.trim($("#dataSource").val()),
            filePath:$.trim($("#fileMultiPath").val()),
            packageName:$.trim($("#packageMultiName").val()),
            mainEntity:$.trim($("#multi_class_bean").val()),
            subEntity:subTableMapping.join(","),
            voName:voList.join("#"),
            searchSql:$("#multiSql").val(),
            httpUrl:$.trim($("#multiUrl").val()),
            classType:classType.join(','),
            mainTable:$("#multi_bean_id").val(),
            mainVo:absSelect.get_form_value("searchMainVo").test
        }

        $.ajax({
            url: '/multiTableCreate',
            type: 'POST',
            data:data,
            dataType: 'json',
            success: function(resp){
                $("body").mLoading("hide");
                if(resp.code==200){
                    alert("SUCCESS");

                }else{
                    alert(resp.message);
                }
            },
            error:function (e) {
                $("body").mLoading("hide");
            }
        });


    })


})

function toHumpName(str) {
    var re = /_(\w)/g; // \w匹配所有的字母和数字字符以及下划线_
    return str.replace(re, function($0, $1) {
        // 第一个参数re表示正则,第二个回调函数,对该字符串处理方式,圆括号内的形参数表示正则表达式的子选项
        return $1.toUpperCase(); // 转大写
    });
}

const loadDataSource = function () {
    $.ajax({
        url: '/getDataSource',
        type: 'POST',
        dataType: 'json',
        success: function(resp){
            if(resp.code==200){
                $("#dataSource").empty();
                $("#dataSource").append('<option value="">--请选择数据源--</option>')
                $.each(resp.data,function(i,v){
                    $("#dataSource").append('<option value="'+v.id+'">'+v.dbSourceName+'</option>')
                });
            }
        }
    });
};


function tabClcik(evt, cityName) {
    $(".tablinks").removeClass("active");
    if(cityName=="tab1"){
        $("#tab2").hide();
        $("#tab1").show();
    }else {
        $("#tab1").hide();
        $("#tab2").show();
    }
    $(evt).addClass("active");

}

function resultGrid(columnsData,resultData) {
    $('#table-baseCode').GM({
        gridManagerName: 'test'
        ,height: '300px'
        ,ajaxData:resultData
        ,columnData: columnsData,
        disableCustomize:true,
        width: '100%'
        // 分页前事件
        ,pagingBefore: function(query){
            console.log('pagingBefore', query);
        }
        // 分页后事件
        ,pagingAfter: function(data){
            console.log('pagingAfter', data);
        }
        // 排序前事件
        ,sortingBefore: function (data) {
            console.log('sortBefore', data);
        }
        // 排序后事件
        ,sortingAfter: function (data) {
            console.log('sortAfter', data);
        }
        // 宽度调整前事件
        ,adjustBefore: function (event) {
            console.log('adjustBefore', event);
        }
        // 宽度调整后事件
        ,adjustAfter: function (event) {
            console.log('adjustAfter', event);
        }
        // 拖拽前事件
        ,dragBefore: function (event) {
            console.log('dragBefore', event);
        }
        // 拖拽后事件
        ,dragAfter: function (event) {
            console.log('dragAfter', event);
        }
    });
}
function plusSelect() {
    if(!$("#bean_id").is(":visible")){
        $(".search-key-multi:visible:last").after($("#multi_last_template").html());
    }else{
        $("#selectDiv:last").after($("#last_template").html());
    }
}
function minusSelect(obj) {
   $(obj).parent().parent().remove();
}

function getMappingLinkId(obj) {
    var data={
        id:$.trim($("#dataSource").val()),
        table:$(obj).val()
    }

    $.ajax({
        url: '/getTablesBean',
        type: 'POST',
        data:data,
        dataType: 'json',
        success: function(resp){
            if(resp.code==200){

                let $select = $(obj).parent().find("select[name='key']");
                $select.empty();
                let data = new Array()
                $.each(resp.data,function(i,v){
                    $select.append('<option value="'+v.name+'">'+v.name+'</option>')

                    let _option={
                        id:v.name,
                        name:v.name
                    }
                    data.push(_option);
                });
                let $searchVo = $(obj).parent().find("div[class='searchVo']");
                if($searchVo.length==0){
                    $searchVo = $(obj).parent().find("div[class='searchVo verjs-select-box']")
                }
                $searchVo.empty()

                let timer1 = new Date().getTime()
                $(obj).parent().append("<input type='hidden' name='searchVo' id='"+timer1+"'>")
                $searchVo.attr("id","searchVo"+timer1)
                let divindex =  (1020-$(".searchVo").length)
                $(".searchVo:visible:last").css({"z-index":divindex});
                absSelect.render({
                    elem: "#searchVo"+timer1,
                    data: data,
                    init_value: [1],
                    body_height: 300,
                    checkbox: true,
                    name: "test"
                });
            }else{
                alert("操作失败");
            }
        }
    });
}